/*
Copyright (c) 2013, Sten Lindgren
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


/*
This program listens to network requests and controls your Tellstick devices
accordingly. Any Tellstick supported by the Telldus Core library is supported.

The program will listen for TCP connections on port 22478. For each
connection it will read and execute requests until the connection is closed.
Requests shall end with a new line, either ^J or ^M or both.

Supported requests:

bell <device>		send bell action to device
dim <device> <level>	set dim level of device
on <device>		turn device on
off <device>		turn device off
exit			close connection (optional)

<device> Telldus numeric device ID or name, where name needs to be enclosed
	 in ' or " if it contains anything but digits and letters or if it
	 starts with a digit
<level>	 dim level 0-100

There is no authentication so anyone with network access to the server
can control your Tellstick devices.

The functionality can be verified using "telnet <hostname> 22478" and
typing the request, like "bell 'front door'".
*/


#define _BSD_SOURCE


#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <telldus-core.h>

#include "lexer.h"
#include "network.h"


#define VERSION		"0.2"

#define DEVICE_NAME_MAX	80	/* max length of Tellstick device name */
#define SERVER_PORT	22478	/* TCP port for communication */


/* struct to hold info about one device */

typedef struct	{
		int	id;				/* device ID */
		char	name[DEVICE_NAME_MAX + 1];	/* device name */
		int	supports_bell;			/* supported methods */
		int	supports_dim;
		int	supports_turnoff;
		int	supports_turnon;
		} device_t;


/* prepare for running as daemon */

void daemonize(void)
	{
	pid_t	pid;
	FILE	*f;

	pid = fork();
	if (pid < 0)
		exit(EXIT_FAILURE);
	else if (pid > 0)
		exit(EXIT_SUCCESS);

	f = fopen("/var/run/tellstick-remote.pid", "w");
	if (!f)
		exit(EXIT_FAILURE);
	fprintf(f, "%d\n", getpid());
	fclose(f);
	}


/* fill device struct with info about Tellstick device */

void get_device(int device_id, device_t *device)
	{
	char	*new_name;
	int	methods;

	new_name = tdGetName(device_id);

	device->id = device_id;
	strncpy(device->name, new_name, DEVICE_NAME_MAX);

	tdReleaseString(new_name);

	methods = tdMethods(device->id, TELLSTICK_BELL |
					TELLSTICK_DIM |
					TELLSTICK_TURNOFF |
					TELLSTICK_TURNON);
	device->supports_bell		= methods & TELLSTICK_BELL;
	device->supports_dim		= methods & TELLSTICK_DIM;
	device->supports_turnoff	= methods & TELLSTICK_TURNOFF;
	device->supports_turnon		= methods & TELLSTICK_TURNON;
	}


/* Lookup Tellstick device by device ID. Return 1 and filled device struct
   if found. Otherwise return 0.
*/

int lookup_device_by_id(int device_id, device_t *device)
	{
	int	index;
	int	device_count;
	int	new_device_id;

	device_count = tdGetNumberOfDevices();
	for (index = 0; index < device_count; index++)
		{
		new_device_id = tdGetDeviceId(index);
		if (new_device_id == device_id)
			{
			get_device(device_id, device);
			return 1;	/* device found */
			}
		}

	return 0;	/* device not found */
	}


/* Lookup Tellstick device by name. Return 1 and filled device struct
   if found. Otherwise return 0.
*/

int lookup_device_by_name(char *device_name, device_t *device)
	{
	int	index;
	int	device_count;
	int	new_device_id;
	char	*new_device_name;

	device_count = tdGetNumberOfDevices();
	for (index = 0; index < device_count; index++)
		{
		new_device_id	= tdGetDeviceId(index);
		new_device_name	= tdGetName(new_device_id);
		if (!strcmp(new_device_name, device_name))
			{
			tdReleaseString(new_device_name);
			get_device(new_device_id, device);
			return 1;	/* device found */
			}
		tdReleaseString(new_device_name);
		}

	return 0;	/* device not found */
	}


int parse_device(device_t *device)
	{
	int	device_id;

	if (next_token.type == TOKEN_TYPE_NUMBER)
		{
		/* trying device ID */
		device_id = next_token.number;
		parse_next_token();

		if (!lookup_device_by_id(device_id, device))
			{
			printf("Unable to find device with ID %d\n", device_id);
			return 0;
			}
		}
	else if ((next_token.type == TOKEN_TYPE_STRING) ||
		 (next_token.type == TOKEN_TYPE_IDENT))
		{
		/* trying device name */
		if (!lookup_device_by_name(next_token.chars, device))
			{
			printf("Unable to find device with name '%s'\n",
			       next_token.chars);

			parse_next_token();
			return 0;
			}
		parse_next_token();
		}
	else
		{
		printf("Expected device ID or name but found %s ('%s')\n",
			token_type_name[next_token.type],
			next_token.chars);

		parse_next_token();
		return 0;
		}

	return 1;
	}


/* print any error from Telldus Core library */

void print_telldus_error(int status, char *action, device_t *device)
	{
	char	*error;

	error = tdGetErrorString(status);
	printf("Request '%s' for device %d (%s) failed with '%s'\n",
		action, device->id, device->name, error);
	tdReleaseString(error);
	}


/* parse bell action */

void parse_bell(void)
	{
	device_t	device;
	int		status;

	parse_next_token();

	if (!parse_device(&device))
		return;

	status = tdBell(device.id);

	if (!status)
		printf("Executed Bell for device %d (%s)\n", device.id, device.name);
	else
		print_telldus_error(status, "Bell", &device);
	}


/* parse dim action */

void parse_dim(void)
	{
	device_t	device;
	int		level;
	int		status;

	parse_next_token();

	if (next_token.type != TOKEN_TYPE_NUMBER)
		{
		printf("Expected number but found %s\n", token_type_name[next_token.type]);
		parse_next_token();
		return;
		}

	level = next_token.number;
	parse_next_token();

	if (level < 0)
		level = 0;
	if (level > 100)
		level = 100;

	if (!parse_device(&device))
		return;

	status = tdDim(device.id, level);
	usleep(200000);
	status = tdDim(device.id, level);

	if (!status)
		printf("Executed Dim %d for device %d (%s)\n",
			level, device.id, device.name);
	else
		print_telldus_error(status, "Dim", &device);
	}


/* parse off action */

void parse_off(void)
	{
	device_t	device;
	int		status;

	parse_next_token();

	if (!parse_device(&device))
		return;

	status = tdTurnOff(device.id);
	usleep(200000);
	status = tdTurnOff(device.id);

	if (!status)
		printf("Executed Off for device %d (%s)\n", device.id, device.name);
	else
		print_telldus_error(status, "Off", &device);
	}


/* parse on action */

void parse_on(void)
	{
	device_t	device;
	int		status;

	parse_next_token();

	if (!parse_device(&device))
		return;

	status = tdTurnOn(device.id);
	usleep(200000);
	status = tdTurnOn(device.id);

	if (!status)
		printf("Executed On for device %d (%s)\n", device.id, device.name);
	else
		print_telldus_error(status, "On", &device);
	}


/* event listener */

void parse_events(void)
	{
	parse_next_token();
	}


/* handle one request from client */

void parse_request(void)
	{
	if (next_token.ident == TOKEN_IDENT_BELL)
		parse_bell();
	else if (next_token.ident == TOKEN_IDENT_DIM)
		parse_dim();
	else if (next_token.ident == TOKEN_IDENT_EVENTS)
		parse_events();
	else if (next_token.ident == TOKEN_IDENT_OFF)
		parse_off();
	else if (next_token.ident == TOKEN_IDENT_ON)
		parse_on();
	else
		{
		printf("Expected action but found %s ('%s')\n",
			token_type_name[next_token.type],
			next_token.chars);
		parse_next_token();
		}
	}


/* Handle new connection, parsing requests until end of data */

void connection_server(int sock)
	{
	tdInit();

	/* prepare parser and get first token */
	parse_start(sock);

	while (next_token.type != TOKEN_TYPE_NONE)
		{
		if (next_token.ident == TOKEN_IDENT_EXIT)
			break;

		parse_request();

		/* ignore rest of line */
		while ((next_token.type != TOKEN_TYPE_NONE) &&
		       (next_token.type != TOKEN_TYPE_END_OF_LINE))
			{
			printf("Ignoring %s '%s' after request\n",
				token_type_name[next_token.type],
				next_token.chars);

			parse_next_token();
			}

		/* skip line endings */
		while (next_token.type == TOKEN_TYPE_END_OF_LINE)
			parse_next_token();
		}

	tdClose();

	close(sock);
	}


/* Loop accepting connections and executing requests. Each connection is
   handled by a separate process.
*/

void socket_server(int listen_socket)
	{
	int	sock;

	printf("Waiting for requests...\n");

	for (;;)
		{
		/* accept a new connection from anywhere */
		sock = accept(listen_socket, NULL, NULL);
		if (sock == -1)
			{
			perror("Failed to accept socket");
			return;
			}

		/* handle new connection in a separate process */
		if (!fork())
			{
			printf("Got new connection...\n");

			close(listen_socket);
			connection_server(sock);

			printf("Connection closed...\n");
			exit(EXIT_SUCCESS);
			}
		else
			{
			close(sock);
			}
		}
	}


/* Open a TCP socket and listen to it.
   Accept any incoming connection and receive one message ending with ch < ' '.
   Close connection and wait for next connection.
*/

int main(int argc, char *argv[])
	{
	int	listen_socket;

	daemonize();

	printf("tellstick-remote version %s\n", VERSION);

	/* ignore exit status from all child processes */
	signal(SIGCHLD, SIG_IGN);

	listen_socket = network_create_listen_socket(SERVER_PORT);
	if (listen_socket > 0)
		{
		socket_server(listen_socket);
		close(listen_socket);
		}

	return EXIT_SUCCESS;
	}
